import { $t } from '@/locales';
// 硬编码常量，避免循环依赖
const REGEXP_WORD_CODE = /^\w+$/;
const VITE_APP_NAME = 'Soybean Admin';

/**
 * Transform record to option
 *
 * @example
 *   ```ts
 *   const record = {
 *     key1: 'label1',
 *     key2: 'label2'
 *   };
 *   const options = transformRecordToOption(record);
 *   // [
 *   //   { value: 'key1', label: 'label1' },
 *   //   { value: 'key2', label: 'label2' }
 *   // ]
 *   ```;
 *
 * @param record
 */
export function transformRecordToOption<T extends Record<string, string>>(record: T) {
  return Object.entries(record).map(([value, label]) => ({
    value,
    label
  })) as CommonType.Option<keyof T>[];
}

/**
 * Translate options
 *
 * @param options
 */
export function translateOptions(options: CommonType.Option<string>[]) {
  return options.map(option => ({
    ...option,
    label: $t(option.label as App.I18n.I18nKey)
  }));
}

/**
 * Toggle html class
 *
 * @param className
 */
export function toggleHtmlClass(className: string) {
  function add() {
    document.documentElement.classList.add(className);
  }

  function remove() {
    document.documentElement.classList.remove(className);
  }

  return {
    add,
    remove
  };
}

/**
 * Generate a fake fetch in a controlled environment like testing
 * @param data response data
 * @param delay time interval
 */
export function createFakeFetch<T = unknown>(data: T, delay = 300) {
  return new Promise<T>((resolve) => {
    setTimeout(() => {
      resolve(data);
    }, delay);
  });
}

/**
 * Format the date to a time ago string
 * @param date date to format
 * @returns formatted string
 */
export function formatDateAgo(date: Date): string {
  const now = new Date();
  const diffInMs = now.getTime() - date.getTime();
  
  const seconds = Math.floor(diffInMs / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  const months = Math.floor(days / 30);
  const years = Math.floor(days / 365);
  
  if (years > 0) {
    return `${years}年前`;
  } else if (months > 0) {
    return `${months}个月前`;
  } else if (days > 0) {
    return `${days}天前`;
  } else if (hours > 0) {
    return `${hours}小时前`;
  } else if (minutes > 0) {
    return `${minutes}分钟前`;
  } else {
    return '刚刚';
  }
}

/**
 * Set the document title
 * @param title title text
 */
export function setDocumentTitle(title: string) {
  document.title = `${title} | ${VITE_APP_NAME}`;
}

/**
 * Get the first letter from the username
 * @param username username text
 */
export function getUsernameFirstLetter(username: string) {
  if (!username) return '';

  return username.charAt(0).toUpperCase();
}

/**
 * Get url search parameters by key when the app is redirected from other page
 * @param key url search parameter key
 */
export function getSearchParameters(key: string) {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get(key);
}

/**
 * Check if the string contains word characters (a-zA-Z0-9_) only
 * @param str string to check
 */
export function isWordCode(str: string) {
  return REGEXP_WORD_CODE.test(str);
}
